<?php
// 
//  MY_strng_helper.php
//  www.6block.com
//  
//  Created by Will_Lee on 2011-06-17.
//  Copyright 2011 lishuzu. All rights reserved.
// 
// 得到首字母
function getfirstletter($string) {
	$string=biconv($string,'gbk','utf-8');
	$dict=array(
		'a'=>0xB0C4,'b'=>0xB2C0,'c'=>0xB4ED,'d'=>0xB6E9,
		'e'=>0xB7A1,'f'=>0xB8C0,'g'=>0xB9FD,'h'=>0xBBF6,
		'j'=>0xBFA5,'k'=>0xC0AB,'l'=>0xC2E7,'m'=>0xC4C2,
		'n'=>0xC5B5,'o'=>0xC5BD,'p'=>0xC6D9,'q'=>0xC8BA,
		'r'=>0xC8F5,'s'=>0xCBF9,'t'=>0xCDD9,'w'=>0xCEF3,
		'x'=>0xD1B8,'y'=>0xD4D0,'z'=>0xD7F9,
		);
	$letter = substr($string, 0, 1);
	$letter_ord = ord($letter);
	if($letter_ord >= 176 && $letter_ord <= 215){
		$num = '0x'.bin2hex(substr($string, 0, 2));
		foreach ($dict as $k=>$v){
			if($v>=$num) break;
		}
		return $k;
	}elseif(($letter_ord>64 && $letter_ord<91) || ($letter_ord>96 && $letter_ord<123)){
		return $letter;
	}elseif($letter>='0' && $letter<='9'){
		return $letter;
	}else{
		return '*';
	}
}

function biconv($str,$to='',$from='',$force=false) {
	if (empty($str)) return $str;
	if(!preg_match( '/[\x80-\xff]/', $str)) return $str; // is contain chinese char
	if(empty($to)){
		$to='utf-8';
	}
	if(empty($from)){
		$from = ('gbk'==strtolower($to)) ? 'utf-8':'gbk';
	}
	$to=strtolower($to);
	$from=strtolower($from);
	//$isutf8=preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $str );
	$re = strlen($str) > 6 ? '/([\xe0-\xef][\x80-\xbf]{2}){2}/' : '/[\xe0-\xef][\x80-\xbf]{2}/';
	$isutf8 = preg_match($re, $str);
	
	//$force = (substr($to, 0, 3) == 'utf') ? true : $force;
	
	if(!$force && $isutf8 && $to=='utf-8' ) return $str;
	if(!$force && !$isutf8 && $to=='gbk' ) return $str;
	
	if (function_exists('iconv')){
		$str = iconv($from, $to, $str);
	}else{
		require_once(APPPATH.'/libraties/Chinese.php');
		$ch = new chinese($from,$to);
		if('utf-8'==$from){
			$str = addslashes($ch->convert(stripslashes($str)));
		}else{
			$str = $ch->convert($str);
		}
	}
	return $str;
}
?>